#include "musiclist.h"
#include <QMimeDatabase>
#include <QDebug>
#include <QSqlQuery>

MusicList::MusicList()
{

}

void MusicList::addMusicsByUrl(const QList<QUrl> &musicUrls)
{
    for(auto e : musicUrls)
    {
        QString path = e.toLocalFile();
        //当前歌曲文件存在,跳过加载
        if(musicPaths.contains(path))
        {
            continue;
        }

        //不存在,路径加入哈希表
        musicPaths.insert(path);

        //将有效的音乐文件添加到musicList中
        //检查文件的mime类型
        QMimeDatabase mimeDB;
        QMimeType mimeType = mimeDB.mimeTypeForFile(e.toLocalFile());
        QString mime = mimeType.name();

        //audio/mepg(表示mp3文件)  audio/flac(无损音乐)  audio/wav
        if(mime == "audio/mpeg" || mime == "audio/flac" || mime == "audio/wav")
        {
            qDebug() << e.toLocalFile();
            Music music(e);
            musicList.push_back(music);
        }
    }
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

iterator MusicList::findMusicById(const QString &musicId)
{
    for(auto it = begin(); it != end(); ++it)
    {
        if(musicId == it->getMusicId())
            return it;
    }

    return end();
}

void MusicList::writeToDB()
{
    for(auto music : musicList)
    {
        music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QSqlQuery query;
    query.prepare("SELECT musicId, musicName, musicSinger, musicAlbum, \
                  musicUrl, musicTime, isLike, isHistory FROM MusicInfo");

    if(!query.exec())
    {
        qDebug() << "数据库查询失败!";
    }

    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbumn(query.value(3).toString());
        music.setMusicUrl("file:///" +query.value(4).toString());
        music.setMusicTime(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        musicList.push_back(music);

        //回复musicPaths,防止相同歌曲重复加载
        musicPaths.insert(music.getMusicUrl().toLocalFile());
    }
}
